package com.sphd.emanu.adapter;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.sphd.emanu.R;

import com.sphd.emanu.pojo.TypeEntity;
import com.wzutils.L;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * @Author Hu
 * @Time 2017/4/26 --17:50.
 * @Email 87683202@qq.com
 */
public class ChooseTypeAdapter extends BaseAdapter {
    Context context;
    List<TypeEntity> typeEntityList;

    public ChooseTypeAdapter(Context context, List<TypeEntity> typeEntityList) {
        this.context = context;
        this.typeEntityList = typeEntityList;
    }

    @Override
    public int getCount() {
        return typeEntityList.size();
    }

    @Override
    public Object getItem(int position) {
        return typeEntityList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder;
        if (convertView == null) {
            convertView = View.inflate(context, R.layout.item_type, null);
            viewHolder = new ViewHolder(convertView);
            convertView.setTag(viewHolder);

        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }
        TypeEntity typeEntity =typeEntityList.get(position);
        viewHolder.typeName.setText(typeEntity.getTypeName());
        if (typeEntity.isSelected()){
            viewHolder.typeFlag.setVisibility(View.VISIBLE);
        }else {
            viewHolder.typeFlag.setVisibility(View.INVISIBLE);
        }
        return convertView;
    }

    static class ViewHolder {
        @BindView(R.id.type_flag)
        TextView typeFlag;
        @BindView(R.id.type_name)
        TextView typeName;

        ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }

    /**
     * 局部更新数据，调用一次getView()方法；Google推荐的做法
     *
     * @param listView 要更新的listview
     * @param position 要更新的位置
     */
    public void notifyDataSetChangedItem(ListView listView, int position) {
        /**第一个可见的位置**/
        int firstVisiblePosition = listView.getFirstVisiblePosition();
        /**最后一个可见的位置**/
        int lastVisiblePosition = listView.getLastVisiblePosition();

        /**在看见范围内才更新，不可见的滑动后自动会调用getView方法更新**/
        if (position >= firstVisiblePosition && position <= lastVisiblePosition) {
            /**获取指定位置view对象**/
            View view = listView.getChildAt(position - firstVisiblePosition);
            getView(position, view, listView);
        }

    }
}
